/**
 * Created by pei on 2019/1/9.
 */
import React, { Component } from 'react';
import {Form, Card, Button, Input, Popconfirm, Select, Checkbox} from 'antd';
import StudentService from '../../service/StudentService';
import NotificationService from '../../service/NotificationService'
import { message } from 'antd';

const Option = Select.Option;

export default class StudentEdit extends Component {

    state = {
        title:'修改积分',
        tableData:[],
        loading:false,
        formItems: [
            {name: '姓名', type: 'textName', fieldName: 'cnName', required: true},
            {name: '现有积分', type: 'text', fieldName: 'score', required: true},
            {name: '积分加减标志', type: 'select', fieldName: 'type', required: true},
            {name: '变化积分', type: 'input', fieldName: 'changeScore', required: true},
            {name: '变化积分原因', type: 'input', fieldName: 'content', required: true},
            {name: '发送积分变化通知', type: 'choice', fieldName: 'send', required: true},
        ],
        selData:{type:[['ADD','增加积分'],['REDUCE','减少积分']]},
        data:{},
        saveDate:{},
        error:false,
        sendFlg:true
    };

    constructor(props) {
        super(props)
    }

    componentDidMount() {
        let id = this.props.match.params.id;
        this.fetch(id);
    }

    fetch(id){
        this.setState({
            loading: true
        });
        StudentService.getOne(id).done((res)=>{
            console.log(res.entity);
            this.setState({data:res.entity,loading: false})
        })
    }

    //页面check
    check(){
        this.state.error = false;

        //积分加减标志check
        if (this.state.data.type === null || this.state.data.type === '' || typeof this.state.data.type === 'undefined') {
            this.state.error = true;
            message.error("请选择积分加减标志！");
            return
        }

        //积分变化check
        if (this.state.data.changeScore === null || this.state.data.changeScore === '' || typeof this.state.data.changeScore === 'undefined') {
            this.state.error = true;
            message.error("请输入变化积分！");
            return
        }
        if (this.state.data.changeScore.length > 5) {
            this.state.error = true;
            message.error("积分变化最多只能输入5个数字！");
            return
        }

        //变化积分原因check
        if (this.state.data.content === null || this.state.data.content === '' || typeof this.state.data.content === 'undefined') {
            this.state.error = true;
            message.error("请输入变化积分原因！");
            return
        }
        if (this.state.data.content.length > 255) {
            this.state.error = true;
            message.error("变化积分原因最多只能输入255个文字！");
            return
        }
    }

    save(){
        //页面check
        this.check();

        if (this.state.error === false) {
            let id = this.props.match.params.id;

            //如果是减少积分，判断是否够扣减，不能出现负数
            if (this.state.data.type !== "ADD") {
                console.log('this.state.date.changeScore', this.state.data.changeScore);
                //扣减时在数字前增加 - 号
                this.state.saveDate.score = this.state.data.changeScore * -1;

                if (parseInt(this.state.data.score) - parseInt(this.state.data.changeScore) < 0) {
                    message.warning("Remaining B-Coin are insufficient to offset!");
                    return
                }
            } else {
                this.state.saveDate.score = this.state.data.changeScore;
            }

            this.state.saveDate.reason = this.state.data.content;
            this.state.saveDate.studentId = id;

            //保存积分变更历史
            StudentService.addScoreHistory(this.state.saveDate).done((res) => {
                console.log(res);

                console.log('this.state.data.content', this.state.data.content);

                //发送通知
                if (this.state.sendFlg === true) {
                    // 积分通知格式：B-Coin change notification: -500. Reason: Activity. B-Coin remain: 100.
                    if (this.state.data.type === "ADD") {
                        this.state.saveDate.content =
                            "B-Coin change notification: " +
                            this.state.data.changeScore + ".Reason: " +
                            this.state.data.content +
                            ". B-Coin remain: " +
                            (parseInt(this.state.data.score) + parseInt(this.state.data.changeScore)) + ".";
                    } else {
                        this.state.saveDate.content =
                            this.state.saveDate.content =
                                "B-Coin change notification: -" +
                                this.state.data.changeScore + ".Reason: " +
                                this.state.data.content +
                                ". B-Coin remain: " +
                                (parseInt(this.state.data.score) - parseInt(this.state.data.changeScore)) + ".";
                    }

                    console.log('this.state.saveDate.content', this.state.saveDate.content);

                    this.state.saveDate.targetUserId = id;
                    NotificationService.addOne(this.state.saveDate)
                }

                message.warning("Change B-Coin successful!");
                this.props.history.goBack();
            });
        }
    }

    //页面渲染
    render() {
        return (
            <Card title={this.state.title}>
                <Form>
                    {this.state.formItems.map((item,i)=>{
                        if(item.type==='input'){
                            return(
                                <Form.Item
                                    label={item.name}
                                    key={i}
                                >
                                    <Input placeholder={"请输入"+item.name} value={this.state.data[item.fieldName]} onChange={(e)=>{
                                        if (item.fieldName === "changeScore") {
                                            this.state.data[item.fieldName] = e.target.value;

                                            if (!isNaN(this.state.data[item.fieldName])) {
                                                //如果第一位数字是0，则把0去掉
                                                this.state.data[item.fieldName] = e.target.value.replace(/^0*/g,'');
                                                this.forceUpdate();
                                            } else {

                                            }
                                        } else {
                                            this.state.data[item.fieldName] = e.target.value;
                                            this.forceUpdate();
                                        }
                                    }}/>
                                </Form.Item>
                            )
                        }else if (item.type==='select') {
                            return(
                                <Form.Item
                                    label={item.name}
                                    key={i}
                                >
                                    <Select placeholder={"请选择" + item.name}
                                            value={this.state.data[item.fieldName]}
                                            onChange={(e)=>{
                                                this.state.data[item.fieldName] = e;
                                                this.forceUpdate();
                                            }}
                                    >
                                        {this.state.selData[item.fieldName].map((item1, j) => {
                                            return (
                                                <Option key={'o_' + j} value={item1[0]}>{item1[1]}</Option>
                                            )
                                        })}
                                    </Select>
                                </Form.Item>
                            )
                        }else if (item.type==='text') {
                            return(
                                <div className="view-item" key={i}>
                                    <span className="view-item-name">{item.name+'：'}</span>
                                    <span className="view-item-text">{this.state.data[item.fieldName]}</span>
                                </div>
                            )
                        }else if (item.type==='textName') {
                            return(
                                <div className="view-item" key={i}>
                                    <span className="view-item-name">{item.name+'：'}</span>
                                    <span className="view-item-text">{this.state.data.firstName} {this.state.data.lastName}</span>
                                </div>
                            )
                        }else if (item.type==='choice') {
                            return(
                                <Form.Item
                                    label={item.name}
                                    key={i}
                                >
                                    <Checkbox checked={this.state.sendFlg} onChange={(e)=>{
                                        this.state.sendFlg = e.target.checked;
                                        this.forceUpdate();
                                    }}/>
                                </Form.Item>
                            )
                        }
                    })}
                    <Form.Item>
                        <Popconfirm placement="top" okText="确认" cancelText="关闭" title="是否确定保存?" onConfirm={() =>{
                            this.save();
                        }}>
                            <Button type="primary" icon="save">保存</Button>
                        </Popconfirm>

                    </Form.Item>
                </Form>
            </Card>
        );
    }
}